package com.piece.core.oauth.social.request;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.oauth.enums.AuthExtendSource;
import com.piece.core.oauth.social.AuthExtendToken;
import lombok.Data;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
import me.zhyd.oauth.utils.UrlBuilder;

public class AuthWeChatMiniProgramRequest extends AuthDefaultRequest {

    public AuthWeChatMiniProgramRequest(AuthConfig config) {
        super(config, AuthExtendSource.WECHAT_MINI_PROGRAM);
    }

    public AuthWeChatMiniProgramRequest(AuthConfig config, AuthStateCache cache) {
        super(config, AuthExtendSource.WECHAT_MINI_PROGRAM, cache);
    }

    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        String response = doPostAuthorizationCode(authCallback.getCode());
        CodeSessionResponse object = JsonUtil.toBean(response, CodeSessionResponse.class);

        this.checkResponse(object);

        AuthExtendToken token = new AuthExtendToken();
        token.setMiniSessionKey(object.sessionKey);
        token.setOpenId(object.openid);
        token.setUnionId(object.unionid);
        return token;
    }

    /**
     * 检查响应内容是否正确
     */
    private void checkResponse(CodeSessionResponse object) {
        if (object.errcode != 0) {
            throw new AuthException(object.errcode, object.errmsg);
        }
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        // 如果需要用户信息，需要在小程序调用函数后传给后端
        /**
         * @Link https://developers.wxpay.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html
         **/
        return AuthUser.builder()
                .uuid(authToken.getOpenId())
                .nickname("")
                .avatar("")
                .token(authToken)
                .source(source.toString())
                .build();
    }

    @Override
    protected String accessTokenUrl(String code) {
        return UrlBuilder.fromBaseUrl(this.source.accessToken())
                .queryParam("appid", this.config.getClientId())
                .queryParam("secret", this.config.getClientSecret())
                .queryParam("js_code", code)
                .queryParam("grant_type", "authorization_code")
                .build();
    }

    @Data
    private static class CodeSessionResponse {
        private int errcode;
        private String errmsg;
        @JsonProperty("session_key")
        private String sessionKey;
        private String openid;
        private String unionid;
    }
}
